package org.wlgzs.office_exam_student.servlet.api;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.wlgzs.office_exam_student.entity.User;
import org.wlgzs.office_exam_student.permission.Authentication;
import org.wlgzs.office_exam_student.servlet.BaseServlet;

import com.songminju.jdagger.JDCheck;

/**
 * @author song(mejeesong@qq.com) 2018年1月25日 验证登录api .
 */
@WebServlet("/api/login")
public class LoginServlet extends BaseServlet {

	private static final long serialVersionUID = 1L;

	// session存储验证码的key
	private final String vCodeImgKey = "verCode";

	private final String reqErrorCode = "reqError";
	private final String reqErrorMsg = "请求格式错误。";

	private final String serverErrorCode = "serverError";
	private final String serverErrorMsg = "网络错误，请刷新重试。";

	private final String successCode = "success";
	private final String successMsg = "登录成功";

	private final String retryCode = "retry";
	private final String retryMsg = "登录失败，请检查账号和密码或者验证码";

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		try {
			processPost(req, resp);
			return;
		} catch (Exception e) {
			e.printStackTrace();
			renderResp(serverErrorCode, serverErrorMsg);
		}
	}

	private void processPost(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		String account = req.getParameter("account");
		String secPassword = req.getParameter("secPassword");
		String vcodeVal = req.getParameter("vcodeVal");
		HttpSession session = req.getSession();
		String realVcode = (String) session.getAttribute(vCodeImgKey);
		logger.debug("receive : account={},secPassword={},vcodeVal={},realVcode={}", account, secPassword, vcodeVal,realVcode);
		if (JDCheck.hasNsNull(account, secPassword, vcodeVal,realVcode)) {
			renderResp(reqErrorCode, reqErrorMsg);
			return;
		}

		if (!realVcode.equalsIgnoreCase(vcodeVal)) {
			renderResp(retryCode, retryMsg);
			return;
		}
		User user = userService.login(account, secPassword);
		if(user==null){
			logger.debug("user==null");
			renderResp(retryCode, retryMsg);
			return;
		}
		logger.debug("登录成功.");
		Authentication.login(session,user);
		renderResp(successCode, successMsg);
	}
	
	private void renderResp(String code, String msg) {
		HttpSession session = threadReq.get().getSession();
		session.removeAttribute(vCodeImgKey);
		logger.debug("i render :{},{}",code,msg);
		renderString(String.format("{code:'%s',msg:'%s'}", code, msg));
	}
}